<template>
    <div class="device-management-container">
        <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="设备名称">
          <el-input v-model="searchForm.name" placeholder="请输入设备名称"></el-input>
        </el-form-item>
        <el-form-item label="设备状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="闲置" :value="0"></el-option>
            <el-option label="已分配" :value="1"></el-option>
            <el-option label="故障" :value="2"></el-option>
            <el-option label="维修中" :value="3"></el-option>
            <el-option label="报废" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工姓名">
          <el-select v-model="searchForm.allocatedEmployee" placeholder="请选择员工" clearable>
            <el-option
              v-for="employee in employeeList"
              :key="employee.jobNumber"
              :label="`${employee.name} (${employee.jobNumber})`"
              :value="employee.jobNumber"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>设备管理</span>
            <el-button type="primary" @click="showAddDialog = true">添加设备</el-button>
            <el-button type="success" @click="showImportDialog = true">批量导入</el-button>
          </div>
        </template>
  <!-- 搜索表单 -->
  
        <el-table :data="deviceList" style="width: 100%" v-loading="loading">
          <el-table-column prop="id" label="设备ID" width="80"></el-table-column>
          <el-table-column prop="name" label="设备名称" width="120"></el-table-column>
          <el-table-column prop="type" label="类型" width="100"></el-table-column>
          <el-table-column prop="location" label="位置" width="150"></el-table-column>
          <el-table-column prop="temperatureRange" label="正常温度" width="100"></el-table-column>
          <el-table-column prop="voltageRange" label="正常电压" width="100"></el-table-column>
          
          <el-table-column prop="status" label="状态" width="120">
            <template #default="{row}">
              <el-tag :type="getStatusTagType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="employeeName" label="分配员工" width="120">
            <template #default="{row}">
              {{ row.employeeName || '未分配' }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="220">
            <template #default="{row}">
              <el-button size="small" @click="handleAllocate(row)">分配</el-button>
              <el-button size="small" type="warning" @click="handleStatusChange(row)">状态</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
              <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.current"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        ></el-pagination>
      </div>
      </el-card>
  
      <!-- 分配设备对话框 -->
      <el-dialog v-model="showAllocateDialog" title="分配设备" width="30%">
        <el-form :model="allocateForm" label-width="100px">
          <el-form-item label="设备名称">
            <el-input v-model="allocateForm.deviceName" disabled></el-input>
          </el-form-item>
          <el-form-item label="分配员工" prop="jobNumber">
            <el-select 
              v-model="allocateForm.jobNumber" 
              filterable 
              placeholder="请选择员工"
              style="width: 100%"
            >
              <el-option
                v-for="employee in employeeList"
                :key="employee.jobNumber"
                :label="`${employee.name} (${employee.jobNumber})`"
                :value="employee.jobNumber"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showAllocateDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmAllocate">确认分配</el-button>
        </template>
      </el-dialog>
  
      <!-- 设备状态对话框 -->
      <el-dialog v-model="showStatusDialog" title="更改设备状态" width="30%">
        <el-form :model="statusForm" label-width="100px">
          <el-form-item label="设备名称">
            <el-input v-model="statusForm.deviceName" disabled></el-input>
          </el-form-item>
          <el-form-item label="当前状态">
            <el-tag :type="getStatusTagType(statusForm.oldStatus)">
              {{ getStatusText(statusForm.oldStatus) }}
            </el-tag>
          </el-form-item>
          <el-form-item label="新状态" prop="newStatus">
            <el-select v-model="statusForm.newStatus" placeholder="请选择状态" style="width: 100%">
              <el-option label="闲置" :value="0"></el-option>
              <el-option label="已分配" :value="1"></el-option>
              <el-option label="故障" :value="2"></el-option>
              <el-option label="维修中" :value="3"></el-option>
              <el-option label="报废" :value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item 
            label="报废原因" 
            prop="scrapReason"
            v-if="statusForm.newStatus === 4"
          >
            <el-input 
              v-model="statusForm.scrapReason" 
              type="textarea" 
              placeholder="请输入报废原因"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showStatusDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmStatusChange">确认更改</el-button>
        </template>
      </el-dialog>
  
      <!-- 添加设备对话框 -->
      <el-dialog v-model="showAddDialog" title="添加新设备" width="30%">
        <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px">
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="addForm.name" placeholder="请输入设备名称"></el-input>
          </el-form-item>
          <el-form-item label="设备类型" prop="type">
            <el-input v-model="addForm.type" placeholder="请输入设备类型"></el-input>
          </el-form-item>
          <el-form-item label="设备位置" prop="location">
            <el-input v-model="addForm.location" placeholder="请输入设备位置"></el-input>
          </el-form-item>
          <el-form-item label="温度范围" prop="temperatureRange">
            <el-input-number v-model="addForm.temperatureRange" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item label="电压范围" prop="voltageRange">
            <el-input-number v-model="addForm.voltageRange" :min="0"></el-input-number>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmAddDevice">确认添加</el-button>
        </template>
      </el-dialog>
      <!-- 批量导入对话框 -->
    <el-dialog v-model="showImportDialog" title="批量导入设备" width="500px">
      <div class="import-container">
        <div class="import-step">
          <h3>第一步：下载模板</h3>
          <el-button 
            type="primary" 
            @click="downloadTemplate"
            icon="el-icon-download"
          >
            下载Excel模板
          </el-button>
        </div>
        
        <div class="import-step">
          <h3>第二步：上传Excel文件</h3>
          <el-upload
            class="upload-demo"
            drag
            action=""
            :auto-upload="false"
            :on-change="handleFileChange"
            :show-file-list="false"
            accept=".xlsx,.xls"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              只能上传xls/xlsx文件，且不超过10MB
            </div>
          </el-upload>
          
          <div v-if="uploadedFile" class="file-info">
            <span>已选择文件: {{ uploadedFile.name }}</span>
            <el-button 
              type="primary" 
              size="mini" 
              @click="submitImport"
              :loading="importLoading"
            >
              开始导入
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
      
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { getAllDevices, allocateDevice, updateDeviceStatus, addDevice, getEmployeeList,
    downloadDeviceTemplate,importDevices } from '../../api/device';
  interface Device {
    id: number;
    name: string;
    type: string;
    location: string;
    status: number;
    temperatureRange: number;
    voltageRange: number;
    scrapReason?: String ;
    createTime: Date;
    employeeName?: string;
  }
  interface Employee {
    jobNumber: number;
    name: string;
  }
  // 设备列表
  const deviceList = ref<Device[]>([]);
  // 员工列表
  const employeeList = ref<Employee[]>([]);
  const loading = ref(false);
  const searchForm = reactive({
  name: '',
  status: null,
  allocatedEmployee: null
});
// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
});
  // 分配设备相关
  const showAllocateDialog = ref(false);
  const allocateForm = reactive({
    deviceId: null,
    deviceName: '',
    jobNumber: null
  });
  
  // 状态变更相关
  const showStatusDialog = ref(false);
  const statusForm = reactive({
    deviceId: null,
    deviceName: '',
    oldStatus: null,
    newStatus: null,
    scrapReason: ''
  });
  
  // 添加设备相关
  const showAddDialog = ref(false);
  const addForm = reactive({
    name: '',
    type: '',
    location: '',
    temperatureRange: 0,
    voltageRange: 0
  });
  const addRules = {
    name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
    type: [{ required: true, message: '请输入设备类型', trigger: 'blur' }],
    location: [{ required: true, message: '请输入设备位置', trigger: 'blur' }]
  };
  const showImportDialog = ref(false);
  const uploadedFile = ref<File | null>(null);
  const importLoading = ref(false);

  
  // 获取设备列表
  const fetchDevices = async () => {
    try {
    loading.value = true;
    const res = await getAllDevices({
      pageNum: pagination.current,
      pageSize: pagination.size,
      name: searchForm.name,
      status: searchForm.status,
      allocatedEmployee:searchForm.allocatedEmployee
    });
    deviceList.value = res.data.records;
    pagination.total = res.data.total;
  } catch (error) {
    ElMessage.error('获取设备列表失败');
  } finally {
    loading.value = false;
  }
  };
  // 搜索
const handleSearch = () => {
  pagination.current = 1;
  fetchDevices();
};

// 重置搜索
const resetSearch = () => {
  searchForm.name = '';
  searchForm.status = null;
  pagination.current = 1;
  fetchDevices();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.size = val;
  fetchDevices();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.current = val;
  fetchDevices();
};
  // 获取员工列表
  const fetchEmployees = async () => {
    try {
      const res = await getEmployeeList();
      employeeList.value = res.data;
    } catch (error) {
      ElMessage.error('获取员工列表失败');
    }
  };
  
  // 状态文本映射
  const getStatusText = (status) => {
    const statusMap = {
      0: '闲置',
      1: '已分配',
      2: '故障',
      3: '维修中',
      4: '报废'
    };
    return statusMap[status] || '未知';
  };
  
  // 状态标签类型
  const getStatusTagType = (status) => {
    const typeMap = {
      0: 'info',
      1: 'success',
      2: 'danger',
      3: 'warning',
      4: ''
    };
    return typeMap[status] || '';
  };
  
  // 分配设备
  const handleAllocate = (row :any) => {
    allocateForm.deviceId = row.id;
    allocateForm.deviceName = row.name;
    allocateForm.jobNumber = row.allocatedEmployee || null;
    showAllocateDialog.value = true;
  };
  
  const confirmAllocate = async () => {
    try {
      await allocateDevice({
        id: allocateForm.deviceId,
        allocatedEmployee: allocateForm.jobNumber
      });
      ElMessage.success('分配成功');
      showAllocateDialog.value = false;
      fetchDevices();
    } catch (error) {
      ElMessage.error('分配失败');
    }
  };
  
  // 更改状态
  const handleStatusChange = (row:any) => {
    statusForm.deviceId = row.id;
    statusForm.deviceName = row.name;
    statusForm.oldStatus = row.status;
    statusForm.newStatus = row.status;
    statusForm.scrapReason = row.scrapReason || '';
    showStatusDialog.value = true;
  };
  
  const confirmStatusChange = async () => {
    try {
      await updateDeviceStatus({
        id: statusForm.deviceId,
        status: statusForm.newStatus,
        scrapReason: statusForm.scrapReason
      });
      ElMessage.success('状态更新成功');
      showStatusDialog.value = false;
      fetchDevices();
    } catch (error) {
      ElMessage.error('状态更新失败');
    }
  };
  
  // 添加设备
  const confirmAddDevice = async () => {
    try {
      await addDevice(addForm);
      ElMessage.success('设备添加成功');
      showAddDialog.value = false;
      fetchDevices();
    } catch (error) {
      ElMessage.error('设备添加失败');
    }
  };
  
  // 下载模板
const downloadTemplate = async () => {
  try {
    const response = await downloadDeviceTemplate();
    console.log(response);
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '设备导入模板.xlsx');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    ElMessage.success('模板下载成功');
  } catch (error) {
    console.error('模板下载失败:', error);
    ElMessage.error('模板下载失败');
  }
};

// 文件选择变化
const handleFileChange = (file: File) => {
  uploadedFile.value = file.raw;
};

// 提交导入
const submitImport = async () => {
  if (!uploadedFile.value) {
    ElMessage.warning('请先选择文件');
    return;
  }

  try {
    importLoading.value = true;
    const formData = new FormData();
    formData.append('file', uploadedFile.value);
    
    const res = await importDevices(formData);
    ElMessage.success(`导入成功，共导入${res.data.successCount}条数据`);
    if (res.data.failureCount > 0) {
      // 如果有失败记录，提供下载错误报告
      const url = window.URL.createObjectURL(new Blob([res.data.errorFile]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', '导入错误报告.xlsx');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      ElMessage.warning(`有${res.data.failureCount}条数据导入失败，已生成错误报告`);
    }
    
    showImportDialog.value = false;
    uploadedFile.value = null;
    fetchDevices(); // 刷新设备列表
  } catch (error) {
    ElMessage.error('导入失败');
  } finally {
    importLoading.value = false;
  }
};

  // 删除设备
  const handleDelete = (row:any) => {
    ElMessageBox.confirm('确定要删除该设备吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        // 调用删除API
        ElMessage.success('删除成功');
        fetchDevices();
      } catch (error) {
        ElMessage.error('删除失败');
      }
    }).catch(() => {});
  };
  
  onMounted(() => {
    fetchEmployees();
    fetchDevices();
    
  });
  </script>
  
  <style scoped>
  .device-management-container {
    padding: 20px;
  }
  
  .box-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
.import-container {
  padding: 0 20px;
}

.import-step {
  margin-bottom: 30px;
}

.import-step h3 {
  margin-bottom: 15px;
  color: #606266;
}

.file-info {
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

  </style>